<?php

namespace App\Http\Controllers\user;

use Validator;
use Mockery\Exception;
use App\Model\User\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RegisterController extends Controller
{
    public function register(Request $request)
    {
        $result = $this->result();
        try
        {
            $request = $this->getRequest($request);
            $Validator = Validator::make($request, [
                'name'       => 'required | min:3 | unique:users,name',
                'email'      => 'required | email | unique:users,email',
                'password'   => 'required | min:5 | max:20| confirmed',
                'student_id' => 'required | min:10| max:10| unique:users,student_id',
            ]);
            //验证失败
            if($Validator->fails())
            {
                //获取错误信息
                $errors = $Validator->errors();
                $result['name']       = $errors->first('name');
                $result['email']      = $errors->first('email');
                $result['password']   = $errors->first('password');
                $result['student_id'] = $errors->first('student_id');
                throw new Exception(config('result.errorRegisterMsg'), config('result.errorRegisterCode'));
            }
            $user = new User();
            $user->name = $request['name'];
            $user->email = $request['email'];
            $user->student_id = $request['student_id'];
            $user->password = bcrypt(request('password'));
            $user->save();
        }
        catch (Exception $exception)
        {
            $result['errorCode'] = $exception->getCode();
            $result['errorMsg']  = $exception->getMessage();
        }

        return $result;
    }

}
